package com.example.web;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author JianpengTong
 * @since 2009-6-24
 * @version 1.0
 */
public class CharacterEncodingFilter implements Filter {

	String encodeName = "UTF-8";

	/**
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * 对请求中的参数进行字符编码
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		// 对 request 请求中的参数进行转码
		request.setCharacterEncoding(encodeName);
		// 设置 response 输出字符编码
		response.setCharacterEncoding(encodeName);
		// 将请求递交到下一个过滤器
		filterChain.doFilter(request, response);
	}

	/**
	 * 初始化字符编码名称[encodeName]
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取 CharacterEncodingFilter 的配置参数
		String arg0 = filterConfig.getInitParameter("encodeName");
		if (arg0 != null){
			encodeName = arg0;
			System.out.println("[信息] set "+filterConfig.getFilterName()+" InitParameter successfully....");
		}else{
			System.out.println("[警告] set "+filterConfig.getFilterName()+" InitParameter failed....");
		}

	}

}